using System;
using System.Linq;

using var db = new BloggingContext();

// Note: This sample requires the database to be created before running.
Console.WriteLine($"Database path: {db.DbPath}.");

// Create
Console.WriteLine("Inserting a new school");
var school = new School { SchoolName = "WHU" };
List<Student> s1 = new List<Student>()
{
    new Student(){StudentName="John"},
    new Student(){StudentName="Jane"}
};
school.Classes = new List<Class>()
{
    new Class(){Grade=1,Students=s1},
    new Class(){Grade=2}
};
db.Add(school);
db.Add(new School { SchoolName = "HUST" });
db.Add(new Log { option = "insert" });
db.SaveChanges();

// Read
Console.WriteLine("Querying for a school");
var sq = db.Schools
    .OrderBy(b => b.SchoolId);
db.Add(new Log { option = "query" });
foreach (var i in sq)
{
    Console.WriteLine("School'name:"+i.SchoolName);
    Console.WriteLine("Classes:");
    foreach (var j in i.Classes)
    {
        Console.WriteLine("Grade:"+ j.Grade);
        Console.WriteLine("Students:");
        foreach (var z in j.Students)
        {
            Console.WriteLine("Name:"+ z.StudentName);
        }
    }
}

// Update
Console.WriteLine("Updating the school");
school.SchoolName ="PKU";
school.Classes.Add(
    new Class { Grade = 2 });
db.SaveChanges();
db.Add(new Log { option = "update" });
// Read
Console.WriteLine("Querying for a school");
var sq2 = db.Schools
    .OrderBy(b => b.SchoolId);
foreach (var i in sq2)
{
    Console.WriteLine("School'name:" + i.SchoolName);
    Console.WriteLine("Classes:");
    foreach (var j in i.Classes)
    {
        Console.WriteLine("Grade:" + j.Grade);
        Console.WriteLine("Students:");
        foreach (var z in j.Students)
        {
            Console.WriteLine("Name:" + z.StudentName);
        }
    }
}

// Delete
Console.WriteLine("Delete the blog");
db.Remove(school);
db.SaveChanges();
db.Add(new Log { option = "delete" });

// Read
Console.WriteLine("Querying for a school");
var sq3 = db.Schools
    .OrderBy(b => b.SchoolId);
foreach (var i in sq3)
{
    Console.WriteLine("School'name:" + i.SchoolName);
    Console.WriteLine("Classes:");
    foreach (var j in i.Classes)
    {
        Console.WriteLine("Grade:" + j.Grade);
        Console.WriteLine("Students:");
        foreach (var z in j.Students)
        {
            Console.WriteLine("Name:" + z.StudentName);
        }
    }
}
// Read
Console.WriteLine("Querying for a school");
var sq4 = db.Logs
    .OrderBy(b => b.LogId);
foreach (var i in sq4)
{
    Console.WriteLine("Option:"+i.option);
}

Console.ReadKey();